import json
from file_manager import *
from tools import *

def handle_content_file():
    content_folder_name = "contents"
    translated_folder_name = "translated"
    json_folder_name = "json"

    pathes = get_new_pull_file_pathes(content_folder_name)
    #1. 添加新的key到translated文件
    #2. 将translated文件转化成json

    for new_file_path in pathes:
        # 1. 添加新的key到translated文件
        translated_file_path = new_file_path.replace(content_folder_name, translated_folder_name)
        if not is_file_exist(translated_file_path):
            create_new_translated_file(new_file_path, translated_file_path)
        else:
            add_new_keys_to_translated_file(new_file_path, translated_file_path)
        # remove suffix '.csv'
        json_file_path = new_file_path.replace(content_folder_name, json_folder_name)[:-4]
        # 2. 将translated文件转化成json
        create_new_json_file(translated_file_path, json_file_path)

# {
#     "This tutorial guides you through building Landmarks — an app for discovering and sharing the places you love. You’ll start by building the view that shows a landmark’s details.":
#     {
#         "zh": "本教程将指导你构建 Landmarks —— 一款发现和分享你喜欢的地方的应用程序。首先你将构建一个用来显示地标详情的视图。",
#         "tips": ""
#     },
# ...


# 对比并添加新的key
def add_new_keys_to_translated_file(content_file_path, translated_file_path):
    if not is_file_exist(translated_file_path) or not is_file_exist(content_file_path):
        return
    content_keys = get_csv_values(content_file_path)
    translated_keys = get_csv_values(translated_file_path)
    new_keys = []
    if not content_keys:
        return
    for new_key in content_keys:
        if new_key in translated_keys:
            continue
        if not new_key in new_keys:
            new_keys.append(new_key)
    write_new_keys_to_csv(translated_file_path, new_keys)

# 创建新的翻译文件
def create_new_translated_file(content_file_path, translated_file_path):
    os.makedirs(os.path.split(translated_file_path)[0], exist_ok=True)
    keys = get_csv_values(content_file_path)
    write_new_keys_to_csv(translated_file_path, keys, "w")

